﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XRPGLibrary.TileEngine;

namespace XRPGLibrary.SpriteClasses
{
    public class AnimatedSprite
    {
        private Dictionary<AnimationKey, Animation> animations;

        private Vector2 position;
        private Texture2D texture;
        private Vector2 velocity;
        private float speed = 2.0f;

        public AnimationKey CurrentAnimation { get; set; }
        public bool IsAnimating { get; set; }
        public int Width
        {
            get { return animations[CurrentAnimation].FrameWidth; }
        }

        public int Height
        {
            get { return animations[CurrentAnimation].FrameHeight; }
        }

        public float Speed
        {
            get { return speed; }
            set { speed = MathHelper.Clamp(speed, 1.0f, 16.0f); }
        }

        public Vector2 Position 
        {
            get { return position; }
            set { position = value; }
        }

        public Vector2 Velocity
        {
            get { return velocity; }
            set 
            { velocity = value;
                  if (velocity != Vector2.Zero)
                      velocity.Normalize();
            }
        }

        public AnimatedSprite(Texture2D sprite, Dictionary<AnimationKey, Animation> animation)
        {
            texture = sprite;
            animations = new Dictionary<AnimationKey, Animation>();
            foreach (AnimationKey key in animation.Keys)
            {
                animations.Add(key, (Animation) animation[key].Clone());
            }
        }

        public void Update(GameTime gameTime)
        {
            if (IsAnimating)
                animations[CurrentAnimation].Update(gameTime);
        }

        public void Draw(GameTime gameTime, SpriteBatch spriteBatch, Camera camera)
        {
            spriteBatch.Draw(
                texture,
                position,
                animations[CurrentAnimation].CurrentFrameRect,
                Color.White);
        }

        public void LockToMap()
        {
            position.X = MathHelper.Clamp(Position.X, 0, TileMap.WidthInPixels - Width);
            position.Y = MathHelper.Clamp(Position.Y, 0, TileMap.HeightInPixels - Height);
        }
    }
}
